package com.soujiayi.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class AsyncSuggestionNameLoader {

	private ExecutorService executorService;
	
	public static final String BAIDU_SUG_REG = "\"[\\s\\S]*?\"";
	
	
	public AsyncSuggestionNameLoader(int threadNumber){
		 executorService = Executors.newFixedThreadPool(threadNumber);
	}
	
	public void getSuggestioName(Handler handler, String key){
		executorService.submit(new getSuggestionNameThread(handler, key));
	}
	
	public class getSuggestionNameThread extends Thread{
		private String key;
		private Handler handler;
		public getSuggestionNameThread(Handler handler, String key){
			this.key = key;
			this.handler = handler;
		}

		@Override
		public void run() {
	        Message msg = new Message();
	        Bundle data = new Bundle();
	        ArrayList<String> keys = findSuggestioName(this.key);
	        data.putStringArrayList("keys", keys);
	        msg.setData(data);
	        handler.sendMessage(msg);
		}
	}
	public ArrayList<String> findSuggestioName(String key) {
		ArrayList<String> list = new ArrayList<String>();

		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet("http://unionsug.baidu.com//su?wd=" + URLEncoder.encode(key, "utf-8"));

			HttpResponse response = client.execute(httpGet);
			InputStream inputStream = response.getEntity().getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					inputStream,"gbk"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + " ");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			String responseStr = sb.toString();
			Pattern pattern = Pattern.compile(BAIDU_SUG_REG);
			Matcher m = pattern.matcher(responseStr);
			
			list.add(key);
			while (m.find()) {
				if(!m.group().replace("\"", "").equals(key)){
					list.add(m.group().replace("\"", ""));
				}
			}

		} catch (Exception e) {
			if(list.size() == 0){
				list.add(key);
			}
		}
		return list;
	}
	
	public void close(){
		executorService.shutdownNow();
	}
}
